package ynu.edu.config;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import ynu.edu.utils.JwtUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 Authorization 头中的 token
        String authorizationHeader = request.getHeader("Authorization");

        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            log.error("Authorization header is missing or incorrect");
            response.setStatus(401);
            return false;
        }

        // 提取 token 字符串（去掉 "Bearer "）
        String token = authorizationHeader.substring(7);

        log.info("从Authorization header中获取token: " + token);

        // 验证 token
        Claims claims = JwtUtils.parseToken(token);

        if (claims == null) {
            // token 是不合法的
            response.setStatus(401);
            return false;
        }

        // 通过验证，允许请求继续处理
        return true;
    }
}
